package com.qdxwx.web.controller.document;

import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.data.service.channel.ChannelService;
import com.qdxwx.data.service.document.DocumentService;
import com.qdxwx.models.category.Category;
import com.qdxwx.models.channel.Channel;
import com.qdxwx.models.document.Document;
import com.qdxwx.models.document.DocumentQuery;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.controller.picture.PictureListController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author MrGao
 */
@Controller
@RequestMapping("/document")
public class DocumentListController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(PictureListController.class);

    @Autowired
    private DocumentService documentService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ChannelService channelService;

    @RequestMapping({"/list.html","/index.html"})
    public String showDocument(HttpServletRequest request, ModelMap mmap) {
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (TKRequest.isMobileBrowse(request)) {
            mmap.put("categoryId", categoryId);
            return getViewPathH5("document/document-list");
        }
        int channelId = TKConvert.toInteger(request.getParameter("channelId"));
        if (channelId == 0) {
            channelId = 11;
        }
        int categoryRootId = 0;
        int categoryParentId = 0;
        String pageTitle = "资料";
        if (categoryId > 0) {
            Category category = categoryService.get(categoryId);
            if (category == null) {
                categoryId = 0;
            } else {
                channelId = category.getChannelId();
                if (category.getParentId() == 0) {
                    categoryRootId = categoryId;
                } else {
                    categoryRootId = category.getParentId();
                }
                categoryParentId = category.getParentId();
                pageTitle = category.getCategoryName() + "-" + pageTitle;
                mmap.put("category", category);
            }
        }
        Channel channel = channelService.get(channelId);
        if (channel == null) {
            return toError404(request);
        }
        //禁用的频道
        if (channel.getIsDisabled() == 1) {
            return toError404(request);
        }
        //判断是否属于模块
        if (channel.getModuleId() != ModuleType.DOCUMENT.ordinal()) {
            return toError404(request);
        }
        // 查询所有1级专业
        List<Category> categoryRoots = categoryService.getRoots(channelId);
        mmap.put("categoryRoots", categoryRoots);
        //查询子专业
        if (categoryId > 0) {
            List<Category> categoryChildren;
            //父Id大于0,获得它的同级专业
            if (categoryParentId <= 0) {
                //获得它的子级专业
                categoryChildren = categoryService.getChildren(categoryId);
            } else {
                Category parent = categoryService.get(categoryParentId);
                if (parent == null) {
                    logger.error("找不到对应父分类（categoryId:" + categoryId + ",parentId:" + categoryParentId + "）");
                    return toErrorView(request, "找不到对应的分类！" + categoryParentId);
                }
                //标题
                pageTitle = parent.getCategoryName() + "-" + pageTitle;
                List<Category> categorySons;
                if (parent.getParentId() <= 0) {
                    //category是二级
                    categoryChildren = categoryService.getChildren(categoryParentId);
                    categorySons = categoryService.getChildren(categoryId);
                    categoryParentId = categoryId;
                } else {
                    //说明category是三级
                    categoryRootId = parent.getParentId();
                    Category root = categoryService.get(categoryRootId);
                    if (root == null) {
                        logger.error("找不到对应父分类（categoryId:" + categoryId + ",parentId:" + categoryParentId + "）");
                        return toErrorView(request, "找不到对应的分类！" + categoryParentId);
                    }
                    pageTitle = root.getCategoryName() + "-" + pageTitle;
                    categoryChildren = categoryService.getChildren(categoryRootId);
                    categorySons = categoryService.getChildren(categoryParentId);
                }
                mmap.put("categorySons", categorySons);
                mmap.put("categoryParent", parent);//父级 专业名
            }
            mmap.put("categoryChildren", categoryChildren);
        }
        mmap.put("pageTitle", pageTitle);
        mmap.put("categoryRootId", categoryRootId);//一级Id
        mmap.put("categoryParentId", categoryParentId);//父级id
        mmap.put("categoryId", categoryId);//id
        int page = TKConvert.toInteger(request.getParameter("page"), 1);
        PageRequest pageRequest = new PageRequest();
        pageRequest.setCurrentPage(page);
        pageRequest.setPageSize(20);

        DocumentQuery params = new DocumentQuery();
        params.setStatus(1);
        params.setCategoryId(categoryId);
        params.setOrderBy(TKConvert.toInteger(request.getParameter("orderBy"), 3));
        params.setIsFree(TKConvert.toInteger(request.getParameter("isFree")));
        params.setLevelId(TKConvert.toInteger(request.getParameter("levelId")));
        if (categoryId > 0) {
            params.setCategoryIds(categoryService.getChildIds(categoryId));
        }
        List<Document> documentList = documentService.getList(params, pageRequest);
        int total = documentService.count(params);
        mmap.put("channel", channel);
        mmap.put("params", params);
        mmap.put("documentList", documentList);
        mmap.put("totalPages", pageRequest.getTotalPages(total));
        mmap.put("page", pageRequest);
        return getViewPath("document/document-list");
    }
}
